package com.kdtech.analyse.outside;
import java.util.Calendar;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;

import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * @author KK
 *
 */
public class TurkistanwebAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.turkistanweb.com/\\?p=[0-9]*",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		title =doc.select(".post-title").text();
		if(StringUtils.isBlank(title))  title =doc.select("title").text();
		if(StringUtils.isBlank(content)) content=HtmlCleaner.getContentHtml(url,doc.select(".viewHandle"));
		if(StringUtils.isBlank(content)) content=HtmlCleaner.getContentHtml(url,doc.select(".content"));
		Elements select=doc.select(".post-meta span");
		if(select.size()>=4){
			Element element=select.get(1);
			String dateStr=element.text();
			if (date==null)date =DateUtils.matchDate(dateStr);
			if (date==null){
				if(dateStr.contains("ago")){
					String[] split=dateStr.split(" ");
					if(split.length>=3){
						String num=split[0];
						String type=split[1];
						Calendar c=Calendar.getInstance();
						if("hours".equalsIgnoreCase(type)){
							 c.add(Calendar.HOUR,-Integer.parseInt(num) );
						}
						if("days".equalsIgnoreCase(type)){
							 c.add(Calendar.DAY_OF_YEAR,-Integer.parseInt(num));
						}
						date=c.getTimeInMillis();
					}
				}
			}
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}

	

	

	
}
